package mianshi.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/16 16:41
 */
//懒汉模式，DCL：双重检测锁  安全性 》 。。。。不安全
public class LazyMan {

    //指令重排，如果不是原子性的操作
        //1.分配内存         1
        //2.执行构造方法     还未执行，对象不完整
        //3.指向地址         2
    // JMM Java内存模型。数据从主内存拿
    private LazyMan(){

    }
    private volatile static LazyMan lazyMan;

    public static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan==null){
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
}

class Demo01{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan instance = LazyMan.getInstance();
        //反射
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan instance2 = declaredConstructor.newInstance();


        System.out.println(instance==instance2);

    }
}